/*
  1: 转发给中转  通过TCP
*/

package httpserver

import (
	//"bytes"
	//"crypto/md5"
	//"encoding/binary"
	"fmt"
	"net"
	//"net/http"
	"sync"
	"time"
	"utils"
)

type WsToTcp struct {
	Conn                *net.TCPConn
	m_cbDataBuffer      [utils.SOCKET_TCP_BUFFER]byte //接受缓冲
	m_NetBuf            *utils.CTCPSocket             //msg 解析
	m_RecvNetBuf        *utils.CTCPSocket             //msg 解析
	m_AssembleBuf       *utils.CTCPSocket
	SysUserLog          *utils.MyLog
	m_Timestamp         uint32
	m_TransType         byte
	m_bvalidationSucces bool
	lock                *sync.Mutex
	m_RecvChan          chan int
	maddr               string
	Closechan           chan bool
}

func MakeNewWsToTcp(RecvChan chan int) *WsToTcp {
	manager := &WsToTcp{
		Conn:                nil,
		lock:                new(sync.Mutex),
		m_bvalidationSucces: false,
		m_RecvChan:          RecvChan,
		Closechan:           make(chan bool),
	}

	manager.m_NetBuf = utils.MarkNewTCPScoket("ProxySercer To CoreServer:", nil)
	manager.m_RecvNetBuf = utils.MarkNewTCPScoket("CoreServer To ProxySercer:", nil)
	manager.m_AssembleBuf = utils.MarkNewTCPScoket("AssembleBuf:", nil)

	for i := 0; i < utils.SOCKET_TCP_BUFFER; i++ {
		manager.m_cbDataBuffer[i] = 0
	}

	return manager
}

func (this *WsToTcp) ConnentFoxServer(addr string) bool {

	if this.Conn == nil {
		this.maddr = addr
		netAddr, err := net.ResolveTCPAddr("tcp", addr)
		if err != nil {
			fmt.Println(fmt.Sprintf("ConnentFoxServer ResolveTCPAddr Error: %s, ERROR:%s", addr, err.Error()))
			return false
		}
		this.Conn, err = net.DialTCP("tcp", nil, netAddr)
		if err != nil {
			fmt.Println(fmt.Sprintf("error connect to server@%s ERROR: %s", addr, err.Error()))
			return false
		}

		if err == nil {
			go this.Start()
		}
		fmt.Println("Create Connect CoreServer Success!")
		return true
	} else {
		fmt.Println("CoreServer Socket Is existed!")
	}

	return true
}

//接受数据
func (this *WsToTcp) Start() {

	for {

		if this.Conn == nil {
			break
		}

		n, err := this.Conn.Read(this.m_cbDataBuffer[:])

		if err == nil {
			this.CallbackToClient(this.m_cbDataBuffer[0:n])
		} else {
			fmt.Println(fmt.Sprintf("RecvServerData -- Failed to read Core server data :error:%s ,length:%d", err.Error(), n))
			this.Close()
			break
		}
		time.Sleep(time.Millisecond * 1)
	}
}

//转发发给前端
func (this *WsToTcp) CallbackToClient(pData []byte) bool {

	//this.m_hc.Write(NewControlErrorDesc(1, "error", nil, 0, 0, 0))
	this.m_RecvChan <- 0
	return true
}

//网络发送
func (this *WsToTcp) SendData(wMainCmdID uint16, wSubCmdID uint16, pData interface{}) bool {

	//Assemble
	SerializeData := this.m_NetBuf.Assemble(wMainCmdID, wSubCmdID, pData, nil)

	if this.Conn != nil {
		//TCP 发送
		n, err := this.Conn.Write(SerializeData)
		if err == nil {
			fmt.Println(fmt.Sprintf("Send Data To CoreServer Success Bytes Size:%d", n))
			return true

		} else {
			fmt.Println(fmt.Sprintf("Send Data To CoreServer Failed Bytes Size:%d", n))
			this.Close()
			return false
		}
	} else {
		fmt.Println(fmt.Sprintf("Send unusual !! the this.Conn = nil"))
	}

	return true
}

//网络关闭
func (this *WsToTcp) Close() {

	fmt.Println("网络关闭")

	this.lock.Lock()
	defer this.lock.Unlock()

	if this.Conn != nil {
		this.Conn.Close()
		this.Conn = nil
		fmt.Println("Close Core Server link")
		this.Closechan <- true
	}

}
